package com.example.chatgpt.database;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.example.chatgpt.dao.MessageDao;
import com.example.chatgpt.dao.UserDao;
import com.example.chatgpt.entity.MessageInfo;
import com.example.chatgpt.entity.UserInfo;

@Database(entities = {MessageInfo.class, UserInfo.class}, version = 2, exportSchema = false)
public abstract class MessageDataBase extends RoomDatabase {

    private static MessageDataBase dataBase;

    public static MessageDataBase getInstance(Context context) {
        if (dataBase == null) {
            dataBase = Room.databaseBuilder(context, MessageDataBase.class, "message.db")
                    .addMigrations(MIGRATION_1_2)
                    .allowMainThreadQueries()
                    .build();
        }
        return dataBase;
    }

    //更新数据库
    public static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            String sql = "CREATE TABLE user (" +
                    "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                    "user TEXT DEFAULT NULL," +
                    "password TEXT DEFAULT NULL)";
            database.execSQL(sql);
            database.execSQL("ALTER TABLE message ADD COLUMN user Text DEFAULT NULL");
        }
    };

    public abstract MessageDao getMessageDao();

    public abstract UserDao getUserDao();
}
